package com.aichat.ai_chatbackend.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.aichat.ai_chatbackend.constant.CommonConstant;
import com.aichat.ai_chatbackend.model.dto.user.UserQueryRequest;
import com.aichat.ai_chatbackend.model.dto.user.UserUpdateMyRequest;
import com.aichat.ai_chatbackend.model.enums.ErrorCode;
import com.aichat.ai_chatbackend.model.enums.UserRoleEnum;
import com.aichat.ai_chatbackend.model.vo.user.UserVO;
import com.aichat.ai_chatbackend.satoken.DeviceUtils;
import com.aichat.ai_chatbackend.service.UserService;
import com.aichat.ai_chatbackend.utils.RedisUtil;
import com.aichat.ai_chatbackend.utils.SqlUtils;
import com.aichat.ai_chatbackend.utils.exception.BusinessException;
import com.aichat.ai_chatbackend.utils.exception.ThrowUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aichat.ai_chatbackend.model.entity.User;
import com.aichat.ai_chatbackend.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DateTime.now;
import static com.aichat.ai_chatbackend.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author yuppie
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-07-13 14:40:37
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private RedisUtil redisUtil;


    private static final String USER_INFO_KEY_PREFIX = "user:info:";


    /**
     * 获取用户封装类
     * @param userId
     * @return
     */
    @Override
    public UserVO getUserVoById(Long userId) {
        User user = this.getById(userId);
        UserVO userVO = UserVO
                .builder()
                .avatarUrl(user.getAvatarUrl())
                .id(user.getId())
                .gender(user.getGender())
                .username(user.getUsername())
                .build();
        return userVO;
    }

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    
    /**
     * 邮箱格式验证正则表达式
     */
    private static final String EMAIL_PATTERN = 
        "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
    
    private static final Pattern EMAIL_REGEX = Pattern.compile(EMAIL_PATTERN);

    /**
     * 验证邮箱格式是否正确
     * @param email 邮箱地址
     * @return true表示格式正确，false表示格式错误
     */
    private boolean isValidEmail(String email) {
        if (StringUtils.isBlank(email)) {
            return false;
        }
        return EMAIL_REGEX.matcher(email).matches();
    }

    @Override
    public long userRegister(String email, String password, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(email, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 验证邮箱格式
        if (!isValidEmail(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        if (password.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!password.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (email.intern()) {
            // 邮箱不能重复（双重检查，确保安全）
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("email", email);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已存在");
            }
            
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());

            QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.orderByDesc("id").last("limit 1");    // 降序选第一个
            User last_user = this.getOne(queryWrapper1);
            long new_user_id;
            if (last_user == null) {
                new_user_id = 1;
            } else {
                new_user_id = last_user.getId() + 1;
            }
            // 3. 插入数据
            User user = new User();
            user.setUsername("用户_" + new_user_id);
            user.setEmail(email);
            user.setPasswordHash(encryptPassword);
            user.setGender(0);
            user.setStatus(1); // 1表示正常状态
            user.setRole("user");
            user.setBirthday(now());
            user.setAvatarUrl("https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png");

            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public UserVO userLogin(String email, String password, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(email, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 邮箱格式验证
        if (!isValidEmail(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        if (password.length() < 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        System.out.println("加密后的密码为:" + encryptPassword);
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        queryWrapper.eq("password_hash", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, username cannot match password");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        StpUtil.login(user.getId(), DeviceUtils.getRequestDevice(request,user.getRole()));
        StpUtil.getSession().set(USER_LOGIN_STATE, user);

        //将登陆信息放入redis缓存 减少对数据库的访问
        return this.getLoginUserVO(user);
    }


    /**
     * 获取当前登录用户
     *
     * @return
     */
    @Override
    public User getCurrentUser() {
        // 先判断是否已登录
        Object loginUserId = StpUtil.getLoginIdDefaultNull();
        if (loginUserId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        User currentUser = (User)StpUtil.getSession().get(USER_LOGIN_STATE);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    @Override
    public Long getCurrentUserId() {
        // 先判断是否已登录
        Object loginUserId = StpUtil.getLoginIdDefaultNull();
        Long userId = null;

        if (loginUserId != null) {
            if (loginUserId instanceof Long) {
                userId = (Long) loginUserId;
                return userId;
            } else if (loginUserId instanceof String) {
                try {
                    userId = Long.parseLong((String) loginUserId);
                    return userId;
                } catch (NumberFormatException e) {
                    // 处理字符串无法转换为 Long 的情况
                    e.printStackTrace();
                }
            } else {
                // 其他类型的处理，根据实际情况决定
                throw new IllegalArgumentException("Unsupported type for loginUserId: " + loginUserId.getClass());
            }
        }
        return null;
    }

    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        return this.getById(userId);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getRole());
    }

    /**
     * 用户注销
     */
    @Override
    public boolean userLogout() {
        Object loginUserId = StpUtil.getLoginIdDefaultNull();
        if (loginUserId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 会自动清除 Redis 中的 Token 和 Session
        StpUtil.logout();
        return true;
    }

    @Override
    public UserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO loginUserVO = new UserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String unionId = userQueryRequest.getUnionId();
        String mpOpenId = userQueryRequest.getMpOpenId();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(unionId), "unionId", unionId);
        queryWrapper.eq(StringUtils.isNotBlank(mpOpenId), "mpOpenId", mpOpenId);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public List<UserVO> getUserListByIds(Set<Long> userIds) {
        List<User> userList =  new ArrayList<>();
        for(Long userId : userIds){
            String key = USER_INFO_KEY_PREFIX + userId;
            User user = (User) redisUtil.getValue(key);
            if(user!=null){
                userList.add(user);
            }else{
                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id",userId);
                User missUser = this.getOne(queryWrapper);
                userList.add(missUser);
                //设置30分钟过期  为什么用 JSON 格式写入 Redis？ 因为missUser是一个对象 需要序列号和反序列化
//                redisUtil.setExValue(key, JSON.toJSONString(missUser), 30,TimeUnit.SECONDS);
                redisUtil.setValue(key,missUser);
            }
        }
        return getUserVO(userList);
    }

    @Override
    public Boolean updateMyUser(UserUpdateMyRequest userUpdateMyRequest) {
        User loginUser = this.getCurrentUser();
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        //判断用户名是否已存在
        if(StrUtil.isNotBlank(user.getUsername())){
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername());
            long count = this.count(queryWrapper);
            User oldUser = this.getOne(queryWrapper);
            long currentUserId = this.getCurrentUserId();
            if (count > 0 && oldUser!=null) {
                if(oldUser.getId()!=currentUserId)
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
            }
        }
        
        //判断邮箱格式和是否已存在
        if(StrUtil.isNotBlank(user.getEmail())){
            // 验证邮箱格式
            if (!isValidEmail(user.getEmail())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
            }
            // 邮箱不能重复
            QueryWrapper<User> emailQueryWrapper = new QueryWrapper<>();
            emailQueryWrapper.eq("email", user.getEmail());
            long emailCount = this.count(emailQueryWrapper);
            User oldEmailUser = this.getOne(emailQueryWrapper);
            long currentUserId = this.getCurrentUserId();
            if (emailCount > 0 && oldEmailUser != null) {
                if(oldEmailUser.getId() != currentUserId)
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已被使用");
            }
        }
        //如果是修改密码
        if (StrUtil.isNotBlank(userUpdateMyRequest.getPassword())) {
            String oldPasswordMd5 = DigestUtils.md5DigestAsHex((SALT + userUpdateMyRequest.getPassword()).getBytes());// 使用加密方式验证原密码是否正确
            if (!oldPasswordMd5.equals(loginUser.getPasswordHash())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "原密码错误");
            }

            String newPassword = userUpdateMyRequest.getNewPassword();
            // 检查密码强度
            if (newPassword.length() < 8) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能小于8位");
            }
//            // 正则检查密码强度(如必须包含数字和字母)
//            if (!newPassword.matches("^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$")) {
//                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码必须包含数字和字母");
//            }
            // 检查两次密码是否一致
            if (!newPassword.equals(userUpdateMyRequest.getConfirmNewPassword())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
            }
            String newPasswordMd5 = DigestUtils.md5DigestAsHex((SALT + newPassword).getBytes());// 使用加密方式验证原密码是否正确
            // 加密新密码
            user.setPasswordHash(newPasswordMd5);
        }
        boolean result = this.updateById(user);
        User newUser = this.getById(loginUser.getId());
        StpUtil.getSession().set(USER_LOGIN_STATE, newUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        String key = USER_INFO_KEY_PREFIX + loginUser.getId();
        redisUtil.setValue(key,newUser);
        return true;
    }


}




